import { useState, useEffect, useRef, useCallback } from 'react';
import type { RequestResponse } from 'umi-request';
import { Spin } from 'antd';
import styles from './index.less';
import ScrollToBottom from 'react-scroll-to-bottom';

function BasicLog<T extends { status: number }>(props: {
  record: T;
  loadStatusAction: () => Promise<RequestResponse<string>>;
}) {
  const { record, loadStatusAction } = props;
  const { status } = record;

  const [rows, setRows] = useState<{ id: number; message: string }[]>([]);
  const timeCacheRef = useRef<NodeJS.Timer>();

  const getLog = useCallback(async () => {
    try {
      const res = await loadStatusAction();
      if (res?.data) {
        const newRows = res.data
          .split('\n')
          .filter((row: string) => !!row)
          .map((row, index) => ({ id: index + 1, message: row }));
        setRows(newRows);
      }
    } catch (e) {}
  }, [loadStatusAction]);

  useEffect(() => {
    getLog();
    if (status === 1) {
      timeCacheRef.current = setInterval(getLog, 2000);
    } else if ([2, 3].includes(status)) {
      if (timeCacheRef.current) clearInterval(timeCacheRef.current);
    }
    return () => {
      if (timeCacheRef.current) clearInterval(timeCacheRef.current);
    };
  }, [status, getLog]);

  return (
    <ScrollToBottom className={styles.logs} followButtonClassName={styles.toBottomBtn}>
      <div style={{ padding: 24 }}>
        {rows.map((row) => (
          <p className={styles.row} key={row.id}>
            {row.message}
          </p>
        ))}
        {status === 1 && (
          <p>
            <Spin spinning size="small" />
          </p>
        )}
      </div>
    </ScrollToBottom>
  );
}

export default BasicLog;
